package com.qf.service.impl;

import com.qf.dao.OrderRepository;
import com.qf.pojo.BaseResp;
import com.qf.pojo.vo.Order;

import com.qf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public BaseResp submit(Order order) {
        Order save = orderRepository.saveAndFlush(order);
        BaseResp baseResp = new BaseResp();
        baseResp.setMessage("提交成功");
        baseResp.setCode(200);
        return baseResp;
    }

    @Override
    public BaseResp findAll(Integer page, Integer size) {
        //查询数据库中的order值
        List<Order> all = orderRepository.findAll();
        //查询redis中是否有该数据
        String key = "order";
        Boolean a = redisTemplate.hasKey(key);
        //如果没有,将数据存入redis中
        if (!a){
            redisTemplate.opsForList().leftPushAll(key,all);
        }
        //如果有,从redis中获取,分页
        int startRow =(page-1)*size;
        int endRow =startRow+size;
        List range = redisTemplate.opsForList().range(key, startRow, endRow - 1);
        //从redis中获取的总的条数
        Long size1 = redisTemplate.opsForList().size(key);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(200);
        baseResp.setMessage("查询成功");
        baseResp.setData(range);
        baseResp.setTotal(size1);
        return baseResp;
    }

    @Override
    public BaseResp del(Integer oid) {
        orderRepository.deleteById(oid);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(200);
        baseResp.setMessage("订单删除成功");
        return baseResp;
    }
}
